import Taro, { Component } from '@tarojs/taro'
import { View, Image, Block, Button } from '@tarojs/components'

import allExtrance from './../../config/allExtrance'
import { Btn, FilterMenu, ConsumerJobList } from './../../component/index'
import './filterJobList.less'

let _this;
class FilterJobList extends Component {

    config = {
        nablePullDownRefresh: true,
        navigationStyle: "custom"
    }

    constructor(props) {
        super(props)
        this.state = {
            // 筛选菜单
            menu: [
                {
                    key: 'sort',
                    value: ['default'],
                    data: [{
                        label: '默认排序',
                        value: 'default',
                        children: []
                    }, {
                        label: '最新发布',
                        value: 'new',
                        children: []
                    }, {
                        label: '离我最近',
                        value: 'distance',
                        children: []
                    }]
                }
            ],
            menuShow: false,
            menuQuery: '',
            // 简历列表
            // 分页
            getDataFinished: false,
            // 定位失败标志
            getLocationFail: false,

            //坐标
            latitude: "",
            longitude: "",
            recomandJobs: [],  //推荐职位
        }
    }

    componentWillReceiveProps(nextProps) {
        console.log(this.props, nextProps)
    }

    componentDidMount() {
        _this = this;
        let recomandJobs = Taro.getStorageSync('recomandJobs')
        if (recomandJobs) {
            this.setState({ recomandJobs: JSON.parse(recomandJobs) })
        }

    }

    componentWillUnmount() { }

    componentDidShow() {
    }

    componentDidHide() { }

    componentWillUpdate() {
    }


    // 初始化菜单数据
    initMenuData() {
        this.setState({
            // menu,
            menuShow: true
        })
        this.getLocation()
            .then(res => {
                let { latitude, longitude } = res
                this.setState({ latitude, longitude })
                this.props.onGetData({ latitude, longitude })
            })

    }

    // 监听筛选菜单组件初始化返回事件
    handleInitMenuResults(e) {
        const menuResults = e
        this
            .initMenuQuery(menuResults)
            .then(res => {
                this.props.onGetData(res)
            })
            .catch(err => { console.log(err) })
    }

    // 初始化查询条件
    initMenuQuery(menuResults) {
        let menuQuery = ''
        menuResults.forEach((item, index) => {
            menuQuery += `&${item.key}=${item.value}`
        })

        this.setState({
            menuQuery
        })

        return this.handleMenuQuery(menuQuery)
    }

    // 更新查询条件
    updateMenuQuery(menuResult) {
        let menuQuery = this.state.menuQuery

        if (menuResult) {
            let regex = new RegExp(`&${menuResult.key}=[^&]+`, "g");
            menuQuery = menuQuery.replace(regex, `&${menuResult.key}=${menuResult.value}`)
        }

        this.setState({
            menuQuery
        })

        return this.handleMenuQuery(menuQuery)
    }

    // 统一处理查询条件
    handleMenuQuery(menuQuery) {
        menuQuery = menuQuery.replace(/&longitude=[^&]+&latitude=[^&]+/g, '')

        if (/sort=distance/.test(menuQuery)) {
            return this
                .getLocation()
                .then(res => {
                    menuQuery += `&longitude=${res.longitude}&latitude=${res.latitude}`
                    this.setState({
                        menuQuery
                    })

                    return menuQuery
                })
                .catch(err => {
                    return Promise.reject('获取位置失败')
                })
        } else {
            this.setState({
                getLocationFail: false
            })
            return Promise.resolve(menuQuery)
        }
    }



    // 筛选后刷新
    refresh(e = {}) {
        const menuResult = e
        // let result = this.props.onResetData('')
        this
            .updateMenuQuery(menuResult)
            .then((res) => {
                this.props.onHandleResetGetData(res)
            })
            .catch(err => { console.log(err) })
    }

    getLocation() {
        return new Promise((resolve, reject) => {
            Taro.getLocation({ type: 'wgs84' }).then(res => {
                resolve(res)
            })
                .catch(err => {
                    Taro.getSetting({
                        success: (res) => {
                            if (res.authSetting['scope.userLocation']) {
                                this.getLocation()
                            } else {
                                // allExtrance.util.Taro.showToast('获取位置失败')
                                // this.setState({
                                //     getLocationFail: true
                                // })
                                // reject()
                                Taro.getSetting().then(resData => {
                                    if (!resData.authSetting['scope.address']) {
                                        Taro.authorize({ scope: 'scope.address' }).then(resultData => {
                                        }).catch(error => {

                                        })
                                    }
                                })
                            }
                        },
                        fail: () => {
                            reject()
                        }
                    })
                })
        })
    }

    openSetting(e) {
        if (e.detail.authSetting['scope.userLocation']) {
            this.setState({
                getLocationFail: false
            })
            this.refresh()
        }
    }

    //获取条件刷新数据
    dealRefresh(menuQuery) {
        let temp = menuQuery;
        let { latitude, longitude } = _this.state
        if (!(latitude && longitude)) {
            this.getLocation()
                .then(res => {
                    temp.latitude = res.latitude;
                    temp.longitude = res.longitude;
                    this.setState({ latitude: res.latitude, longitude: res.longitude })
                    this.props.onGetData(temp)
                })
                .catch(err => {
                    console.log(err)
                })
        } else {
            temp.latitude = latitude;
            temp.longitude = longitude;
            this.props.onGetData(temp)
        }
    }

    render() {
        let { menuShow, fixed, getLocationFail, getDataFinished, menu, recomandJobs } = this.state;
        return (
            <View className='index'>
                {/* <!-- 筛选菜单 --> */}
                <View className={fixed} style='top: 64px'>
                    {
                        menuShow && <Block>
                            <FilterMenu isSearch={this.props.isSearch} onDealRefresh={this.dealRefresh} menu={menu} onInitMenuResults={this.handleInitMenuResults} onSelectFinish={this.refresh} eleHeight={this.props.eleHeight}></FilterMenu>
                        </Block>
                    }
                </View>
                {/* <!-- 工作列表 --> */}
                {
                    this.props.jobs.length || this.props.firstInter ? <Block>
                        <ConsumerJobList jobs={this.props.jobs}></ConsumerJobList>
                        {getDataFinished && <View className='finished-tip'>没有数据啦~</View>}
                    </Block> : <Block>
                            <View className='empty-result-box'>
                                {/* <Image className='icon' src='https://file.open.banchengyun.com/2019/04/01/155410773632097.png' /> */}
                                <View className='text'>没有匹配的职位，修改搜索条件再试试~</View>
                                {/* {getLocationFail && <Btn my-class='authorize-btn val' open-type='openSetting' onOpenSetting={this.openSetting.bind(this)} title='授权地理位置'></Btn>} */}
                                {getLocationFail && <Button open-type='openSetting'>授权地理位置</Button>}
                            </View>
                            <View className='recommandBlock'>
                                <View className='recommand'>为您推荐以下好职位</View>
                            </View>
                            <ConsumerJobList jobs={recomandJobs}></ConsumerJobList>
                        </Block>
                }
            </View>
        )
    }
}

export default FilterJobList
